import json
import os
import django
import sys
import uuid

# 设置项目路径和Django环境变量
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "baoxian.settings")
django.setup()

from pydantic import BaseModel, Field
from langchain.tools import StructuredTool
from langchain.tools import tool
from insurance.models import ClaimOrder
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.domain.AlipayFundTransToaccountTransferModel import AlipayFundTransToaccountTransferModel
from alipay.aop.api.request.AlipayFundTransToaccountTransferRequest import AlipayFundTransToaccountTransferRequest

class AlipayTransferSchema(BaseModel):
    id_number: str = Field(..., description="身份证号，18位")
    claim_amount: str = Field(..., description="理赔金额")

def alipay_transfer_func(id_number: str, claim_amount: str) -> str:
    claim_order = ClaimOrder.objects.filter(
        insurance__id_number=id_number,
        claim_amount=str(claim_amount),
        status='待支付'
    ).first()

    if not claim_order:
        return "未找到符合条件的待转账理赔订单"

    merchant_account = "ouciqb3604@sandbox.com"
    user_account = claim_order.insurance.alipay_account
    amount = claim_order.claim_amount

    client_config = AlipayClientConfig()
    client_config.server_url = "https://openapi-sandbox.dl.alipaydev.com/gateway.do"
    client_config.app_id = "9021000150657773"
    with open(r"D:\model\P4\sandbox_private_key.pem", "r", encoding="utf-8") as f:
        client_config.app_private_key = f.read()
    with open(r"D:\model\P4\alipay_public_key.pem", "r", encoding="utf-8") as f:
        client_config.alipay_public_key = f.read()

    client = DefaultAlipayClient(alipay_client_config=client_config)

    out_biz_no = "ORDER" + uuid.uuid4().hex.upper()
    biz_model = AlipayFundTransToaccountTransferModel()
    biz_model.out_biz_no = out_biz_no
    biz_model.payee_type = "ALIPAY_LOGONID"
    biz_model.payee_account = str(user_account)
    biz_model.amount = str(amount)
    biz_model.payer_show_name = "商家名称"
    biz_model.payee_real_name = str(claim_order.insurance.name)
    biz_model.remark = "保险理赔转账"

    request = AlipayFundTransToaccountTransferRequest(biz_model=biz_model)

    try:
        before_response = client.execute(request)
        response = json.loads(before_response)
        if response and response.get("code") == "10000":
            claim_order.alipay_transfer_id = response.get("order_id", out_biz_no)
            claim_order.status = "已支付"
            claim_order.save()
            return (f"成功从商家账户 {merchant_account} 转账 {amount} 元 到用户账户 {user_account}，"
                    f"支付宝流水号：{claim_order.alipay_transfer_id}")
        else:
            claim_order.status = "支付失败"
            claim_order.fail_reason = response.get("sub_msg", "未知错误")
            claim_order.save()
            return f"转账失败：{claim_order.fail_reason}"
    except Exception as e:
        claim_order.status = "支付失败"
        claim_order.fail_reason = str(e)
        claim_order.save()
        return f"转账异常：{str(e)}"

alipay_transfer = StructuredTool.from_function(
    func=alipay_transfer_func,
    name="alipay_transfer",
    description="根据身份证号和金额，执行支付宝转账并更新订单状态。",
    args_schema=AlipayTransferSchema,
)
